package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.data.Result;
import com.dongdongshop.data.ResultEnum;
import com.dongdongshop.data.content.CartListRedis;
import com.dongdongshop.pojo.cart.Cart;
import com.dongdongshop.pojo.seller.TbItem;
import com.dongdongshop.pojo.user.TbUser;
import com.dongdongshop.service.ItemService;
import com.dongdongshop.service.cart.CartServiceI;
import com.dongdongshop.utils.CookieUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Controller
@RequestMapping("cartController")
public class CartController {

    @Reference
    private CartServiceI cartServiceI;//自定义的 拼接购物车
    @Reference
    private ItemService itemService;
    private final Logger logger = LoggerFactory.getLogger(CartController.class);

    //加入购物车跳转页面
    @RequestMapping("addCart")
    public String addCart(HttpServletRequest request, HttpServletResponse response, Long itemId, Integer num, Model model){
        setCart(request,response,itemId,num);
        TbItem item = itemService.getItemById(itemId);
        model.addAttribute("item",item);
        model.addAttribute("num",num);
        return "success-cart";

    }
    @RequestMapping("toCart")
    public String toCart(){
        return "cart";
    }
    //获取购物车
    @RequestMapping("getCart1")
    @ResponseBody
    public Result getCart1(HttpServletRequest request,HttpServletResponse response){
        System.out.println("111111111");
        //判断用户是否登录 1.没登录查询cookie 2.登录走redis
        TbUser user =(TbUser) SecurityUtils.getSubject().getPrincipal();
        try {
            //从cookie这个中获取购物车信息，原因之前可能存在购物车，我们需要先查询出来，然后判断信息，拼接购物车
            String cartListstr = CookieUtils.getCookieValue(request, CartListRedis.CARTLIST, "UTF-8");
            //判断购物车如果为空，我们防止空指针
            if (StringUtils.isBlank(cartListstr)){
                cartListstr="[]";//防止报空指针 因为是个lIst集合写""不行
            }
            //将字符串转成List集合
            List<Cart> cartList = JSONObject.parseArray(cartListstr, Cart.class);//Cart.class 是public List<Cart> getCart里的Cart
            if (user == null){
               return Result.response(ResultEnum.OK).setData(cartList);
            }else {
                //从redis中查询出购物车列表
                List<Cart> cartListFromRedis = cartServiceI.getCartListFromRedis(user.getUsername());
                //判断cookie中是否有数据
                if (cartList.size()>0){//有数据就添加到redis中，反之不添加
                    //合并购物车
                    cartListFromRedis= cartServiceI.mergeCartListCookieAndRedis(cartList,cartListFromRedis);
                    //将合并得购物车，存放到redis
                    cartServiceI.saveCartListToRedis(user.getUsername(),cartListFromRedis);
                    //清楚cookie中得购物车
                    CookieUtils.deleteCookie(request,response,CartListRedis.CARTLIST);
                }
                return Result.response(ResultEnum.OK).setData(cartListFromRedis);
            }
        }catch (Exception e){
            logger.error("操作异常",e);
            return Result.response(ResultEnum.FAIL);
        }
       // return Result.response(ResultEnum.OK).setData("成功");
    }



    /*以下为上课练习
    前台页面不登录，商品加入购物车后 能看到加入购物车
    获取购物车
    */
    @RequestMapping("getCart")
    @ResponseBody
    public List<Cart> getCart(HttpServletRequest request, HttpServletResponse response){
        //判断用户是否登录 1.没登录查询cookie 2.登录走redis
        TbUser user =(TbUser) SecurityUtils.getSubject().getPrincipal();
            //从cookie这个中获取购物车信息，原因之前可能存在购物车，我们需要先查询出来，然后判断信息，拼接购物车
            String cartListstr = CookieUtils.getCookieValue(request, CartListRedis.CARTLIST, "UTF-8");
            //判断购物车如果为空，我们防止空指针
            if (StringUtils.isBlank(cartListstr)){
                cartListstr="[]";//防止报空指针 因为是个lIst集合写""不行
            }
        //将字符串转成List集合
        List<Cart> cartList = JSONObject.parseArray(cartListstr, Cart.class);//Cart.class 是public List<Cart> getCart里的Cart
        if (user == null){

            return cartList;
        }else {
            //从redis中查询出购物车列表
            List<Cart> cartListFromRedis = cartServiceI.getCartListFromRedis(user.getUsername());
            //判断cookie中是否有数据
            if (cartList.size()>0){//有数据就添加到redis中，反之不添加
                //合并购物车
                cartListFromRedis= cartServiceI.mergeCartListCookieAndRedis(cartList,cartListFromRedis);
                //将合并得购物车，存放到redis
                cartServiceI.saveCartListToRedis(user.getUsername(),cartListFromRedis);
                //清楚cookie中得购物车
                CookieUtils.deleteCookie(request,response,CartListRedis.CARTLIST);
            }
            return cartListFromRedis;
        }

    }

    //享购物车内添加数据
    @RequestMapping("setCart")
    @ResponseBody
    public Result setCart(HttpServletRequest request, HttpServletResponse response,Long itemId,Integer num){
       // System.out.println("进入方法");
        //判断用户是否登录 1.没登录查询cookie 2.登录走redis
        TbUser user=(TbUser)SecurityUtils.getSubject().getPrincipal();
     //先从cookie中获取购物车的数据  直接调用上面getCart()方法
        List<Cart> cartList = getCart(request, response);
        //调用dubbo组装购物车  cartList原来的购物车数据 增加时需要商品的id和数量num
        try {
            //是组装数据不考虑登录不登录
            cartList=cartServiceI.addCartList(cartList,itemId,num);//增加之后覆盖原来(上面)的cartList
           if (user == null){
               CookieUtils.setCookie(request,response,CartListRedis.CARTLIST,JSONObject.toJSONString(cartList),true);
           }else {
               cartServiceI.saveCartListToRedis(user.getUsername(),cartList);
           }
        }catch (Exception e){
            e.printStackTrace();
            return Result.response(ResultEnum.FAIL);
        }
        System.out.println("添加方法");
       return Result.response(ResultEnum.OK);
    }
}
